package com.ztom.top100;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 反转二叉树
 * <p>
 * https://leetcode-cn.com/problems/invert-binary-tree/
 *
 * @author ZhangTao
 */
public class Code65InvertTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归
     *
     * @param root
     * @return
     */
    public TreeNode invertTree1(TreeNode root) {
        if (root == null) {
            return null;
        }

        process(root);
        return root;
    }

    private void process(TreeNode node) {
        if (node == null) {
            return;
        }
        // 叶子节点
        if (node.left == null && node.right == null) {
            return;
        }
        TreeNode tmp = node.left;
        node.left = node.right;
        node.right = tmp;
        process(node.left);
        process(node.right);
    }

    /**
     * 迭代
     *
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode node = null;
        while (!queue.isEmpty()) {
            node = queue.poll();
            if (node == null) {
                continue;
            }
            if (node.left == null && node.right == null) {
                continue;
            }
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;

            queue.add(node.left);
            queue.add(node.right);
        }
        return root;
    }
}
